import 'package:get/get.dart';
import 'package:orginone/dart/base/schema.dart';
import 'package:orginone/dart/core/public/enums.dart';
import 'package:orginone/dart/core/thing/standard/application.dart';
import 'package:orginone/dart/core/work/index.dart';
import 'package:orginone/main.dart';

class AssetsManagementLogic extends GetxController {
  static AssetsManagementLogic getLogic() {
    if (Get.isRegistered<AssetsManagementLogic>()) {
      return Get.find<AssetsManagementLogic>();
    }
    return Get.put(AssetsManagementLogic());
  }

  RxList<IApplication> applications = <IApplication>[].obs;
  RxInt currentIndex = (-1).obs;

  RxList<IWork> allIworkWithNoType = <IWork>[].obs;
  @override
  void onReady() {
    super.onReady();
    initData();
  }

  initData() async {
    applications.clear();
    List<IApplication> app = await relationCtrl.loadApplications();
    // 初始化延迟加载的数据，这里延迟了3秒
    Future.delayed(Duration(seconds: app.isEmpty ? 3 : 0), () async {
      applications.value = app
          .where((element) =>
              // element.name == "资产管理" &&
              !element.groupTags.contains("已删除") &&
              element.directory.target.typeName != DirectoryType.storage.label)
          .toSet()
          .toList();

      XApplication? cacheApp = await relationCtrl.user!.cacheObj
          .get<XApplication>('assetmodule', XApplication.fromJson);
      if (cacheApp != null) {
        IApplication? res = applications.value
            .firstWhereOrNull((element) => element.id == cacheApp.id);
        if (res != null) {
          currentIndex.value = applications.value.indexOf(res);
          loadWorks();
        }
      }
      if (currentIndex.value < 0) {
        currentIndex.value = 0;
        getAllFormsAndWorks(currentIndex.value);
        loadWorks();
      }
    });
  }

  loadWorks() async {
    if (applications.isEmpty) return;
    allIworkWithNoType.value =
        await applications[currentIndex.value].loadWorks();
  }

  getAllFormsAndWorks(int i) async {
    if (i < 0 || applications.isEmpty) return;
    // allIform.value = await applications[i].loadAllForms();
    // allIwork.value = await applications[i].loaAlldWorks();
    // print("forms num==${allIform.length}     works num==${allIwork.length}");
  }
}
